package com.pinhuba.bams.framework.util;

import com.pinhuba.bams.framework.exception.AirPlaneModeException;
import com.pinhuba.bams.framework.exception.NoInternetException;

import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Environment;
import android.provider.Settings;

public class PhoneStateUtil {

	public static boolean isAirplaneModeOn() {
		return (Settings.System.getInt(MyApplication.getAppContext().getContentResolver(), Settings.System.AIRPLANE_MODE_ON, 0) != 0);
	}

	public static boolean isAirplaneModeOn(Context context) {
		return (Settings.System.getInt(context.getContentResolver(), Settings.System.AIRPLANE_MODE_ON, 0) != 0);
	}

	public static boolean hasInternet() {
		ConnectivityManager manager = (ConnectivityManager) MyApplication.getAppContext().getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo info = manager.getActiveNetworkInfo();
		if (info != null && info.isConnected()) {
			if (info.getState() == NetworkInfo.State.CONNECTED) {
				return true;
			}
		}
		return false;
	}

	public static boolean hasInternet(Activity mActivity) {
		ConnectivityManager manager = (ConnectivityManager) mActivity.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo info = manager.getActiveNetworkInfo();
		if (info != null && info.isConnected()) {
			if (info.getState() == NetworkInfo.State.CONNECTED) {
				return true;
			}
		}
		return false;
	}

	/**
	 * Whether the memory card in writing form 记忆卡是否处于可写状态
	 * 
	 * @Title: exterStorageReady
	 * @return true,false
	 */
	public static boolean exterStorageReady() {
		// Get SdCard state
		if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) && Environment.getExternalStorageDirectory().canWrite()) {
			return true;

		}
		return false;
	}

	public static boolean checkNetWork() throws AirPlaneModeException, NoInternetException {
		if (!hasInternet()) {
			if (isAirplaneModeOn()) {
				throw new AirPlaneModeException();
			}
			throw new NoInternetException();
		}
		return true;
	}

	public static boolean checkNetWork(Activity act) throws AirPlaneModeException, NoInternetException {
		if (!hasInternet(act)) {
			if (isAirplaneModeOn(act)) {
				throw new AirPlaneModeException();
			}
			throw new NoInternetException();
		}
		return true;
	}
}
